import requests
import json
import pandas as pd


url = "https://slamdunk.sports.sina.com.cn/api?p=radar&callback=jQuery111304806610526772176_1746771564824&p=radar&s=team_standing&a=conference&_=1746771564825"
response = requests.get(url)
if response.status_code == 200:
    data_text = response.text
    try:
        # 处理JSONP格式数据，提取JSON部分
        start_index = data_text.find('{')
        end_index = data_text.rfind('}') + 1
        json_data_str = data_text[start_index:end_index]
        json_data = json.loads(json_data_str)
        all_teams_data = []
        # 提取东部球队数据
        for team in json_data.get('result', {}).get('data', {}).get('eastern', []):
            team_info = {
                "conference": "Eastern",
                "team_name": team.get('team_name'),
                "wins": team.get('wins'),
                "losses": team.get('losses'),
                "win_rate": team.get('win_pct')
            }
            all_teams_data.append(team_info)
        # 提取西部球队数据
        for team in json_data.get('result', {}).get('data', {}).get('western', []):
            team_info = {
                "conference": "Western",
                "team_name": team.get('team_name'),
                "wins": team.get('wins'),
                "losses": team.get('losses'),
                "win_rate": team.get('win_pct')
            }
            all_teams_data.append(team_info)
        # 转换为DataFrame并保存为CSV文件
        df = pd.DataFrame(all_teams_data)
        csv_file_path = "2023_2024_nba_rankings.csv"
        df.to_csv(csv_file_path, index=False, encoding="utf-8-sig")
        print(f"数据已成功写入 {csv_file_path}")
        # 转换为JSON格式并保存为JSON文件
        json_file_path = "2023_2024_nba_rankings.json"
        with open(json_file_path, "w", encoding="utf-8") as json_file:
            json.dump(all_teams_data, json_file, ensure_ascii=False, indent=4)
        print(f"数据已成功写入 {json_file_path}")
    except json.JSONDecodeError as e:
        print(f"JSON解析错误: {e}")
        print(f"原始数据: {data_text}")
else:
    print(f"请求失败，状态码: {response.status_code}")
